package com.system.enterprisemanagementsystem.controller;

import com.system.enterprisemanagementsystem.anno.LogOperation;
import com.system.enterprisemanagementsystem.exception.BusinessException;
import com.system.enterprisemanagementsystem.pojo.*;
import com.system.enterprisemanagementsystem.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/clazzs")
@RestController
public class  ClazzController {

    @Autowired
    ClazzService clazzService;

    /**
     * 条件分页查询
     * @param clazzQueryParam
     * @return
     */
    @GetMapping
    public Result page(ClazzQueryParam clazzQueryParam) {
        log.info("查询请求参数： {}", clazzQueryParam);

        PageResult pageResult = clazzService.page(clazzQueryParam);

        return Result.success(pageResult);
    }

    @GetMapping("list")
    public Result list(){
        log.info("查询所有班级");
        List<Clazz> clazzList = clazzService.clazzList();
        return Result.success(clazzList);
    }

    @PostMapping
    @LogOperation
    public Result addClazz(@RequestBody Clazz clazz) {
        log.info("添加班级");
        clazzService.addClazz(clazz);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result getClazzById(@PathVariable Integer id) {

        log.info("根据id查询班级");

        return Result.success(clazzService.queryClazzById(id));
    }

    @PutMapping
    @LogOperation
    public Result updateClazz(@RequestBody Clazz clazz) {
        log.info("更新班级信息 clazz{}",clazz);
        clazzService.updateClazz(clazz);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @LogOperation
    public Result deleteClazz(@PathVariable Integer id) {
        log.info("删除班级请求, id: {}", id);

        // 参数校验
        if (id == null || id <= 0) {
            return Result.error("参数错误");
        }

        try {
            // 1、检查班级是否存在
            Clazz clazz = clazzService.queryClazzById(id);
            if (clazz == null) {
                return Result.error("班级不存在");
            }

            // 2、检查关联学生
            int studentCount = clazzService.getStudentCountByClazzId(id);
            if (studentCount > 0) {
                return Result.error("该班级下存在 " + studentCount + " 名学生，无法删除");
            }

            // 3、执行删除
            clazzService.deleteClazzById(id);
            return Result.success("删除成功");

        } catch (BusinessException e) {
            log.warn("删除班级业务异常, id: {}", id, e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("删除班级系统异常, id: {}", id, e);
            return Result.error("系统异常，删除失败");
        }
    }


}
